package com.example.recycleview;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class MainActivity6 extends AppCompatActivity {
    private EditText editText,editText2;
    private TextView textView;
    private Button buttonSp1,buttonSp2;
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main6);
        editText=findViewById(R.id.editTextNumberPassword);
        editText2=findViewById(R.id.editTextNumberPassword2);
        buttonSp1=findViewById(R.id.buttonSp1);
        buttonSp2=findViewById(R.id.buttonSp2);
        textView=findViewById(R.id.textViewSp);
        sp=getSharedPreferences("chf", Context.MODE_PRIVATE);//Context.MODE_PRIVATE表示其他文件无法访问这个sp文件
        editor=sp.edit();
        File file = new File("/data/data/com.example.recycleview/chf2");
        buttonSp1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    FileOutputStream fos =new FileOutputStream(file);
                    fos.write(editText.getText().toString().trim().getBytes());
                    fos.write("#".getBytes());
                    fos.write(editText2.getText().toString().trim().getBytes());
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                editor.putString("id",editText.getText().toString().trim());
                editor.putString("key",editText2.getText().toString().trim());
                editor.commit();

            }
        });
        buttonSp2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                textView.setText(sp.getString("id","")+sp.getString("key",""));
                try {
                    FileInputStream fis = new FileInputStream(file);
                    BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                    String[] string = br.readLine().split("#");
                    textView.setText(string[0]+string[1]);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}